<template>
	<view class="content">
		<view class="header">
			<text class="title">登录</text>
		</view>
		<view class="tabs">
			<text class="tab" :class="{ active: loginType === 'phone' }" @click="setLoginType('phone')">
				手机号登录
			</text>
			<text class="tab" :class="{ active: loginType === 'password' }" @click="setLoginType('password')">
				密码登录
			</text>
		</view>
		<view v-if="loginType === 'phone'" class="input-group">
			<input type="number" v-model="user.phone" placeholder="请输入手机号" maxlength="11" />
		</view>
		<view v-if="loginType === 'phone'" class="input-group code-input-group">
			<input type="number" v-model="user.code" placeholder="请输入验证码" maxlength="6" />
			<button class="get-code-btn" @click="getCode" :disabled="isCounting">
				{{ isCounting ? `${countdown}秒后重试` : '获取验证码' }}
			</button>
		</view>
		<view v-if="loginType === 'password'" class="input-group">
			<input type="text" v-model="user.phone" placeholder="请输入用户名/手机号" />
		</view>
		<view v-if="loginType === 'password'" class="input-group">
			<input type="password" v-model="user.password" placeholder="请输入密码" />
		</view>
		<view class="login-button">
			<button @click="login">登录</button>
		</view>
		<view class="switch-login">
			<text v-if="loginType === 'phone'" @click="setLoginType('password')">密码登录</text>
			<text v-if="loginType === 'password'" @click="setLoginType('phone')">手机号登录</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onUnmounted
	} from 'vue';
	import {
		useTokenStore
	} from '@/stores/jwt.js';
	import {
		useuser
	} from '../../stores/User.js';
	import {
		http
	} from '../../config/request.js';

	const loginType = ref('phone');
	const user = ref({
		username: '',
		password: '',
		phone: '',
		code: ''
	});

	// 新增倒计时相关变量
	const isCounting = ref(false);
	const countdown = ref(60);
	let timer = null;

	const setLoginType = (type) => {
		loginType.value = type;
	};

	// 改进的手机号验证函数 - 使用正则表达式
	const validatePhone = (phone) => {
		const reg = /^1[3-9]\d{9}$/;
		if (!reg.test(phone)) {
			uni.showToast({
				title: '请输入正确的11位手机号',
				duration: 2000,
				icon: 'error'
			});
			return false;
		}
		return true;
	};

	// 保持原有密码验证不变
	const validatePassword = (password) => {
		if (password.length < 6) {
			uni.showToast({
				title: '密码长度不能小于6位',
				duration: 2000,
				icon: 'error'
			});
			return false;
		}
		return true;
	};

	// 保持原有登录逻辑不变
	const login = () => {
		var phone = user.value.phone;
		if (loginType.value === 'phone') {
			var code = user.value.code;
			if (!phone) {
				uni.showToast({
					title: '手机号不能为空',
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			if (!validatePhone(phone)) return;
			if (!code) {
				uni.showToast({
					title: '验证码不能为空',
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			yanzhengma()
		} else if (loginType.value === 'password') {
			var phone = user.value.phone;
			var password = user.value.password;
			if (!phone) {
				uni.showToast({
					title: '用户名/手机号不能为空',
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			if (!password) {
				uni.showToast({
					title: '密码不能为空',
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			if (!validatePassword(password)) return;
			denglu();
		}
	};

	// 修改后的获取验证码逻辑，添加倒计时
	const getCode = async () => {
		const phone = user.value.phone;
		console.log(phone);
		// 先验证手机号格式
		if (!validatePhone(phone)) return;

		if (isCounting.value) return;

		try {
			const result = await http({
				url: '/yanzheng/' + phone,
				method: 'get',
			});

			if (result.code == 20041) {
				uni.showToast({
					title: '验证码发送成功',
					duration: 2000,
					icon: 'success'
				});
				// 开始倒计时
				startCountdown();
			} else {
				uni.showToast({
					title: '验证码发送失败',
					duration: 2000,
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('获取验证码失败:', error);
			uni.showToast({
				title: '验证码发送失败',
				duration: 2000,
				icon: 'error'
			});
		}
	};

	// 新增倒计时方法
	const startCountdown = () => {
		isCounting.value = true;
		countdown.value = 60;
		timer = setInterval(() => {
			countdown.value--;
			if (countdown.value <= 0) {
				clearInterval(timer);
				isCounting.value = false;
			}
		}, 1000);
	};
	// 组件卸载时清除定时器
	onUnmounted(() => {
		if (timer) clearInterval(timer);
	});
	// 保持原有验证码验证逻辑不变
	const yanzhengma = async () => {
		const phone = user.value.phone
		const code = user.value.code
		const yan = await http({
			url: '/zhuce/' + phone + "/" + code,
			method: 'get',
		})
		console.log(yan)
		if (yan.code == 20041) {
			uni.showToast({
				title: '登陆成功',
				duration: 2000,
				icon: 'success',
			});
			useTokenStore().jwt = yan.shuju.jwt;
			useuser().setuser(yan.shuju.user)
			uni.switchTab({
				url: '/pages/homepage/index',
				method: 'get'
			})
		} else {
			uni.showToast({
				title: '验证码错误',
				duration: 2000,
				icon: 'error'
			});
		}
		// uni.switchTab({
		// 	url: '/pages/homepage/index'
		// })
	}

	// 保持原有登录逻辑不变
	const denglu = async () => {
		try {
			const jieguo = await http({
				url: '/queryyonghu',
				data: user.value,
				method: 'post'
			});
			console.log(jieguo);
			if (jieguo.code == 20041) {
				uni.showToast({
					title: '登陆成功',
					duration: 2000,
					icon: 'success'
				});
				useTokenStore().jwt = jieguo.shuju.jwt;
				useuser().user = jieguo.shuju.duixiang;
				uni.switchTab({
					url: '/pages/homepage/index'
				});
			} else if (jieguo.code === 400) {
				uni.showToast({
					title: '请求参数错误',
					duration: 2000,
					icon: 'error'
				});
			} else if (jieguo.code === 401) {
				uni.showToast({
					title: '未授权，请重新登录',
					duration: 2000,
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({
				title: '登录失败，请检查网络或联系管理员',
				duration: 2000,
				icon: 'error'
			});
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20px;
		background-color: #ffffff;
		font-family: Arial, sans-serif;
		font-size: 16px;
		line-height: 1.5;
	}

	.header {
		text-align: center;
		margin-bottom: 20px;
	}

	.title {
		font-size: 24px;
		font-weight: bold;
		color: #007aff;
	}

	.tabs {
		display: flex;
		justify-content: space-around;
		width: 100%;
		max-width: 300px;
		margin-bottom: 20px;
	}

	.tab {
		font-size: 16px;
		color: #666;
		cursor: pointer;
	}

	.tab.active {
		color: #007aff;
		border-bottom: 2px solid #007aff;
	}

	.input-group {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		width: 100%;
		max-width: 300px;

		input {
			flex: 1;
			padding: 10px;
			border: 1px solid #ccc;
			border-radius: 5px;
			margin-right: 10px;
		}
	}

	.code-input-group {
		.get-code-btn {
			white-space: nowrap;
			padding: 10px 15px;
			font-size: 14px;
			background-color: #007aff;
			color: white;
			border: none;
			border-radius: 5px;
			cursor: pointer;

			&:disabled {
				background-color: #ccc;
				cursor: not-allowed;
			}
		}
	}

	.login-button {
		width: 100%;
		max-width: 300px;
		margin-top: 20px;

		button {
			width: 100%;
			padding: 10px;
			background-color: #007aff;
			color: white;
			border: none;
			border-radius: 5px;
			cursor: pointer;
		}
	}

	.switch-login {
		margin-top: 20px;
		font-size: 14px;
		color: #007aff;
		cursor: pointer;
	}
</style>